//package com.gaga.console.core.service.impl;
//
//import cn.hutool.core.lang.Assert;
//import cn.hutool.core.thread.ThreadUtil;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.gaga.common.constant.BvConstants;
//import com.gaga.common.enums.*;
//import com.gaga.common.exception.BusException;
//import com.gaga.console.base.entity.sse.PushMessageDto;
//import com.gaga.console.base.mybatisplus.LambdaQueryWrapperExt;
//import com.gaga.console.base.utils.MyDecimalUtil;
//import com.gaga.console.base.utils.MyStringUtil;
//import com.gaga.console.base.utils.SseEmitterServerUtils;
//import com.gaga.console.base.utils.VideoPlayerUtils;
//import com.gaga.console.core.entity.BvScriptCategory;
//import com.gaga.console.core.entity.BvScriptItem;
//import com.gaga.console.core.entity.dto.*;
//import com.gaga.console.core.entity.vo.TextToSpeechVo;
//import com.gaga.console.core.service.*;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//
//import java.io.File;
//import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.LinkedHashMap;
//import java.util.List;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ThreadLocalRandom;
//import java.util.stream.Collectors;
//
///**
// * <p>
// * 用户信息表 服务实现类
// * </p>
// *
// * @author liujia
// * @since 2025-03-27
// */
//@Service
//public class BvAudioPlayServiceImplbackup implements BvAudioPlayService {
//
//    private static final Logger log = LoggerFactory.getLogger(BvAudioPlayServiceImplbackup.class);
//
//    // 使用 ConcurrentHashMap 作为缓存存储直播间人数
//    private final ConcurrentHashMap<String, String> userCountCache = new ConcurrentHashMap<>();
//
//    // 使用 ConcurrentHashMap 作为缓存播放日志路径
//    private final ConcurrentHashMap<String, String> playLogPathCache = new ConcurrentHashMap<>();
//
//    public static final String USER_COUNT_KEY = "userCount";
//
//    public static final String PLAY_LOG_PATH = "playLogPath";
//
//    @Autowired
//    private SysConfigService sysConfigService;
//
//    @Autowired
//    private BvScriptItemService bvScriptItemService;
//
//    @Autowired
//    private BvScriptCategoryService bvScriptCategoryService;
//
//    @Autowired
//    private BvModelService bvModelService;
//
//    @Autowired
//    private BvConfigService bvConfigService;
//
//    @Autowired
//    private AudioQueueService audioQueueService;
//
//    @Autowired
//    private AssistantService assistantService;
//
//    private volatile boolean isStop = false;
//
//    private volatile boolean switchStatus = false;
//
//    @Override
//    public void startLive(StartLiveDto dto) {
//        Assert.notNull(dto.getCategoryId(), "分类id不能为空");
//
//        //死循环判断模型得0进程是否已停止
////        while (!assistantService.canRunModel()) {
////            ThreadUtil.sleep(5000); // 等待1秒
////        }
//
//        //开启模型
//        assistantService.startModel();
//
//        //死循环判断模型是否已启动，启动后再向下执行
//        while (!assistantService.isModelRunning()) {
//            ThreadUtil.sleep(1000); // 等待1秒
//        }
//
//        LambdaQueryWrapperExt<BvScriptItem> wraps = new LambdaQueryWrapperExt<>();
//        wraps.eq(BvScriptItem::getDelFlag, DelFlag.OK.getCode());
//        wraps.eq(BvScriptItem::getScriptCategoryId, dto.getCategoryId());
//        wraps.eq(BvScriptItem::getScriptType, ScriptType.MAIN_AUDIO.getCode());
//
//        List<BvScriptItem> scriptList = bvScriptItemService.list(wraps);
//        if (CollectionUtils.isEmpty(scriptList)) {
//            throw new BusException("请先维护话术脚本");
//        }
//
//        isStop = false;
//        audioQueueService.stopLive();
//
//        BvScriptCategory scriptCategory = bvScriptCategoryService.getById(dto.getCategoryId());
//
//        //主音频按照文件名排序
//        MyStringUtil.sortByName(scriptList);
//
//        String playLogFilePath = sysConfigService.getConfigValueByKey(BvConstants.PLAY_LOG_FILE_PATH);
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        String formattedDateTime = sdf.format(new Date());
//        long timestamp = System.currentTimeMillis();
//
//        // 播放日志文件名
//        String playLogPath = playLogFilePath + File.separator + "play_log_" + formattedDateTime + "_" + timestamp + ".log";
//        playLogPathCache.put(PLAY_LOG_PATH, playLogPath);
//        Path playLogFile = Paths.get(playLogPath);
//
//        try {
//            Files.createDirectories(playLogFile.getParent());
//            // 2. 创建文件
//            if (!Files.exists(playLogFile)) {
//                Files.createFile(playLogFile);
//                log.info("直播日志文件创建成功！" + playLogPath);
//            }
//        } catch (IOException e) {
//            log.error(e.getMessage());
//        }
//
//        ThreadUtil.execute(() -> {
//
//            while (!isStop) {
//                Integer anchorQueueSize = audioQueueService.getQueueSize(PlayerType.ANCHOR);
//
//                //如果队列中已经有超过10个音频文件，则等待
//                if (anchorQueueSize <= 10) {
//                    mainAudioTts(scriptList, playLogPath,scriptCategory.getScriptCategoryName());
//                }
//                ThreadUtil.sleep(5000);
//            }
//        });
//    }
//
//    private void mainAudioTts(List<BvScriptItem> scriptList, String playLogPath, String categoryName) {
//
//        String generateAudioPathConfig = sysConfigService.getConfigValueByKey(BvConstants.GENERATE_AUDIO_PATH);
//        LinkedHashMap<String, List<BvScriptItem>> itemNameMap = scriptList.stream()
//                .parallel()
//                .collect(Collectors.groupingBy(
//                        BvScriptItem::getItemName,
//                        LinkedHashMap::new,
//                        Collectors.toList()
//                ));
//        for (String itemName : itemNameMap.keySet()) {
//            Integer queueSizeByScriptType = audioQueueService.getQueueSizeByScriptType(ScriptType.MAIN_AUDIO);
//
//            //如果队列中已经有超过10个音频文件，则等待
//            while (true) {
//                queueSizeByScriptType = audioQueueService.getQueueSizeByScriptType(ScriptType.MAIN_AUDIO);
//                if (queueSizeByScriptType < 15) {
//                    break;
//                }
//                ThreadUtil.sleep(3000);
//            }
//            String generateAudioPath = generateAudioPathConfig;
//
//            ConfigDto configDto = bvConfigService.getConfig();
//            Boolean smartReplyOpen = configDto.getMainAudioSetting().getSmartReply().getOpen();
//            Integer intervalMin = configDto.getMainAudioSetting().getIntervalMin();
//            Integer intervalMax = configDto.getMainAudioSetting().getIntervalMax();
//
//            String blockWords = configDto.getSmartReplySetting().getBlockWords();
//            String liveRoomDesc = configDto.getSmartReplySetting().getLiveRoomDesc();
//            Long modelId = configDto.getSmartReplySetting().getModelId();
//            String token = configDto.getSmartReplySetting().getToken();
//
//            String refAudioPath = sysConfigService.getConfigValueByKey(BvConstants.REF_AUDIO_PATH);
//            String promptText = sysConfigService.getConfigValueByKey(BvConstants.PROMPT_TEXT);
//            String currentModelName = sysConfigService.getConfigValueByKey(BvConstants.CURRENT_MODEL_NAME);
//
//            //生成音频文件路径
//            if (!generateAudioPath.endsWith(File.separator)) {
//                generateAudioPath = generateAudioPath + File.separator;
//            }
//            generateAudioPath = generateAudioPath + categoryName + File.separator + ScriptType.MAIN_AUDIO.getCode() + File.separator + currentModelName + File.separator;
//
//            List<BvScriptItem> bvScriptItems = itemNameMap.get(itemName);
//            if (CollectionUtils.isEmpty(bvScriptItems)) {
//                continue;
//            }
//            BvScriptItem scriptItem = bvScriptItems.get(0);
//
//            if (StringUtils.isBlank(scriptItem.getScriptContent())) {
//                continue;
//            }
//
//            if (ScriptItemFileType.FOLDER.getCode().equals(bvScriptItems.get(0).getItemFileType())) {
//                int randomIndex = ThreadLocalRandom.current().nextInt(bvScriptItems.size());
//                BvScriptItem bvScriptItem = bvScriptItems.get(randomIndex);
//
//                String scriptContent = bvScriptItem.getScriptContent();
//
//                // 去除开头的斜杠（适用于 Windows 文件系统）
//                if (scriptContent.startsWith("/") && System.getProperty("os.name").contains("Windows")) {
//                    scriptContent = scriptContent.substring(1);
//                }
//
//                AudioDto audioDto = new AudioDto().setAudioFilePath(scriptContent)
//                        .setPlayScriptId(bvScriptItems.get(0).getId().toString())
//                        .setScriptType(ScriptType.MAIN_AUDIO)
//                        .setPlayLogPath(playLogPathCache.get(PLAY_LOG_PATH))
//                        .setIntervalMin(intervalMin)
//                        .setIntervalMax(intervalMax)
//                        .setSpeed(MyDecimalUtil.getFloatSpeed(configDto.getAudioSetting().getPlay()))
//                        .setVolume(MyDecimalUtil.getFloatVolume(configDto.getAudioSetting().getVolume().getLocal()));
//                //正在播放的音频播放完成后插入到第一条
//                audioQueueService.addToQueue(audioDto, PlayerType.ANCHOR);
//                continue;
//            }
//
//            String[] lines = StringUtils.split(scriptItem.getScriptContent(), "\r\n");
//            int randomIndex = ThreadLocalRandom.current().nextInt(lines.length);
//            String text = lines[randomIndex];
//
//            TextToSpeechFrontDto textToSpeechFrontDto = getTextToSpeechFrontDto(text, configDto.getModelSetting());
//            textToSpeechFrontDto.setPlayerType(PlayerType.ANCHOR);
//            if (scriptItem.getItemName().contains("小助理")) {
//                textToSpeechFrontDto.setPlayerType(PlayerType.ASSISTANT);
//            }
//            String modelName = currentModelName;
//            if (PlayerType.ANCHOR.equals(textToSpeechFrontDto.getPlayerType())) {
//                modelName = configDto.getModelSetting().getAnchor();
//            } else if (PlayerType.ASSISTANT.equals(textToSpeechFrontDto.getPlayerType())) {
//                modelName = configDto.getModelSetting().getAssistant();
//            }
//            if (!currentModelName.equals(modelName)) {
//                switchStatus = true;
//                bvModelService.switchModel(modelName);
//            }
//
//            //生成音频文件路径
//            String tempPath = generateAudioPath + scriptItem.getItemName() + File.separator + System.currentTimeMillis() + BvConstants.WAV_FORMAT;
//            textToSpeechFrontDto.setGenerateAudioPath(tempPath);
//            textToSpeechFrontDto.setPromptText(promptText);
//            textToSpeechFrontDto.setRefAudioPath(refAudioPath);
//
//            //构建智能回复参数
//            if (smartReplyOpen) {
//                textToSpeechFrontDto.setSmartReply(true);
//                textToSpeechFrontDto.setModelId(modelId);
//                textToSpeechFrontDto.setBlockWords(blockWords);
//                textToSpeechFrontDto.setLiveRoomDesc(liveRoomDesc);
//                textToSpeechFrontDto.setToken(token);
//            }
//
//            try {
//                textToSpeechFrontDto.setChannelId(configDto.getSseChannelId());
//                textToSpeechFrontDto.setScriptType(ScriptType.MAIN_AUDIO);
//                TextToSpeechVo textToSpeechVo = bvModelService.textToSpeech(textToSpeechFrontDto);
//                String audioFilePath = textToSpeechVo.getAudioFilePath();
//                if (StringUtils.isBlank(audioFilePath)) {
//                    continue;
//                }
//                if (isStop) {
//                    break;
//                }
//                AudioDto audioDto = new AudioDto().setAudioFilePath(audioFilePath)
//                        .setScriptType(ScriptType.MAIN_AUDIO)
//                        .setText(textToSpeechVo.getFinalText())
//                        .setOldText(textToSpeechVo.getOldText())
//                        .setChannelId(configDto.getSseChannelId())
//                        .setPlayScriptId(scriptItem.getId().toString())
//                        .setScriptCategoryId(configDto.getFileDirectory().getCategoryId())
//                        .setPlayFileName(scriptItem.getItemName())
//                        .setPlayLogPath(playLogPath)
//                        .setIsSmartReply(smartReplyOpen)
//                        .setIntervalMin(intervalMin)
//                        .setIntervalMax(intervalMax)
//                        .setSpeed(MyDecimalUtil.getFloatSpeed(configDto.getAudioSetting().getPlay()))
//                        .setVolume(MyDecimalUtil.getFloatVolume(configDto.getAudioSetting().getVolume().getLocal()));
//                audioQueueService.addToQueue(audioDto, textToSpeechFrontDto.getPlayerType());
//            } catch (Exception e) {
//                log.error(e.getMessage());
//            }
//        }
//    }
//
//    @Override
//    public void stopLive() {
//        isStop = true;
//        audioQueueService.stopLive();
//        VideoPlayerUtils.closeWindow();
////        assistantService.shutDownModel();
//
//        ConfigDto config = bvConfigService.getConfig();
//
//        List<PushMessageType> needCleanTypeList = PushMessageType.getNeedCleanTypeList();
//        for (PushMessageType pushMessageType : needCleanTypeList) {
//            PushMessageDto pushMessageDto = new PushMessageDto();
//            pushMessageDto.setMessage("");
//            pushMessageDto.setType(pushMessageType);
//            SseEmitterServerUtils.sendMessage(config.getSseChannelId(), pushMessageDto);
//        }
//
//        log.info("停止直播");
//    }
//
//    @Override
//    public void generate(PlayDto dto) {
//
//        // 判断是否打开关键字回复或者用户进入
//        ConfigDto configDto = bvConfigService.getConfig();
//        Boolean open = false;
//        Boolean smartReplyOpen = false;
//        Boolean smartQA = false;
//        Long modelId = configDto.getSmartReplySetting().getModelId();
//        String blockWords = configDto.getSmartReplySetting().getBlockWords();
//        String liveRoomDesc = configDto.getSmartReplySetting().getLiveRoomDesc();
//        String token = configDto.getSmartReplySetting().getToken();
//        switch (dto.getScriptType()) {
//            case KEYWORD:
//                open = configDto.getKeywordSetting().getOpen();
//                smartReplyOpen = configDto.getKeywordSetting().getSmartReply().getOpen();
//                smartQA = configDto.getKeywordSetting().getOpenSmartQA();
//                break;
//            case USER_ENTER:
//                open = configDto.getUserEnterSetting().getOpen();
//                smartReplyOpen = configDto.getUserEnterSetting().getSmartReply().getOpen();
//                break;
//            default:
//                open = true;
//                break;
//        }
//        if (!open) {
//            return;
//        }
//
//        String currentModelName = sysConfigService.getConfigValueByKey(BvConstants.CURRENT_MODEL_NAME);
//        String generateAudioPath = sysConfigService.getConfigValueByKey(BvConstants.GENERATE_AUDIO_PATH);
//        if (StringUtils.isBlank(currentModelName)) {
//            throw new BusException("请先选择模型");
//        }
//
//        if (ScriptType.RANDOM_AUDIO.equals(dto.getScriptType())) {
//            QueryWrapper<BvScriptItem> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("category_id", configDto.getFileDirectory().getCategoryId());
//            queryWrapper.eq("script_type", dto.getScriptType().getCode());
//            List<BvScriptItem> list = bvScriptItemService.list(queryWrapper);
//            if (CollectionUtils.isEmpty(list)) {
//                return;
//            }
//            int index = ThreadLocalRandom.current().nextInt(list.size());
//            BvScriptItem bvScriptItem = list.get(index);
//            if (StringUtils.isBlank(bvScriptItem.getScriptContent())) {
//                return;
//            }
//            if (bvScriptItem.getScriptContent().endsWith(BvConstants.WAV_FORMAT)) {
//                //是音频文件直接播放
//                if (isStop) {
//                    return;
//                }
//                AudioDto audioDto = new AudioDto().setAudioFilePath(bvScriptItem.getScriptContent())
//                        .setScriptType(dto.getScriptType())
//                        .setPlayLogPath(playLogPathCache.get(PLAY_LOG_PATH))
//                        .setVolume(MyDecimalUtil.getFloatVolume(configDto.getAudioSetting().getVolume().getLocal()));
//                //正在播放的音频播放完成后插入到第一条
//                audioQueueService.insertFirstToQueue(audioDto, PlayerType.ANCHOR);
//                return;
//            } else {
//                dto.setText(bvScriptItem.getScriptContent());
//            }
//        }
//
//        try {
//            String modelName = getAudioModelName(dto, configDto);
//
//            if (!currentModelName.equals(modelName)) {
//                bvModelService.switchModel(modelName);
//            }
//
//            String refAudioPath = sysConfigService.getConfigValueByKey(BvConstants.REF_AUDIO_PATH);
//            String promptText = sysConfigService.getConfigValueByKey(BvConstants.PROMPT_TEXT);
//
//            TextToSpeechFrontDto textToSpeechFrontDto = getTextToSpeechFrontDto(dto.getText(), configDto.getModelSetting());
//            //根据配置信息获取发音人
//            String speaker = getSpeaker(dto, configDto);
//            textToSpeechFrontDto.setPlayerType(PlayerType.getPlayerTypeByCode(speaker));
//            textToSpeechFrontDto.setUserName(dto.getUserName());
//            textToSpeechFrontDto.setPromptText(promptText);
//            textToSpeechFrontDto.setRefAudioPath(refAudioPath);
//            textToSpeechFrontDto.setRepeatProblem(configDto.getKeywordSetting().getRepeatProblem());
//            textToSpeechFrontDto.setProblemText(configDto.getKeywordSetting().getProblemText());
//
//            //构建智能回复参数
//            textToSpeechFrontDto.setSmartQA(smartQA);
//            textToSpeechFrontDto.setSmartReply(smartReplyOpen);
//            textToSpeechFrontDto.setModelId(modelId);
//            textToSpeechFrontDto.setBlockWords(blockWords);
//            textToSpeechFrontDto.setLiveRoomDesc(liveRoomDesc);
//            textToSpeechFrontDto.setToken(token);
//
//            //生成音频文件路径
//            if (!generateAudioPath.endsWith(File.separator)) {
//                generateAudioPath = generateAudioPath + File.separator;
//            }
//            generateAudioPath = generateAudioPath + modelName + File.separator + dto.getScriptType().getCode() + File.separator + System.currentTimeMillis() + BvConstants.WAV_FORMAT;
//            textToSpeechFrontDto.setGenerateAudioPath(generateAudioPath);
//
//            textToSpeechFrontDto.setChannelId(configDto.getSseChannelId());
//            textToSpeechFrontDto.setScriptType(dto.getScriptType());
//            TextToSpeechVo textToSpeechVo = bvModelService.textToSpeech(textToSpeechFrontDto);
//            String audioFilePath = textToSpeechVo.getAudioFilePath();
//            if (StringUtils.isBlank(audioFilePath)) {
//                return;
//            }
//            if (isStop) {
//                return;
//            }
//
//            LambdaQueryWrapperExt<BvScriptItem> bvScriptItemQueryWrapper = new LambdaQueryWrapperExt<>();
//            bvScriptItemQueryWrapper.eq(BvScriptItem::getScriptType, dto.getScriptType().getCode());
//            bvScriptItemQueryWrapper.eq(BvScriptItem::getDelFlag, DelFlag.OK.getCode());
//            bvScriptItemQueryWrapper.eq(BvScriptItem::getScriptCategoryId, configDto.getFileDirectory().getCategoryId());
//            List<BvScriptItem> list = bvScriptItemService.list(bvScriptItemQueryWrapper);
//            Long scriptId = null;
//            if (!CollectionUtils.isEmpty(list)) {
//                scriptId = list.get(0).getScriptCategoryId();
//            }
//
//            AudioDto audioDto = new AudioDto().setAudioFilePath(audioFilePath)
//                    .setScriptType(dto.getScriptType())
//                    .setText(textToSpeechVo.getFinalText())
//                    .setOldText(textToSpeechVo.getOldText())
//                    .setChannelId(configDto.getSseChannelId())
//                    .setPlayLogPath(playLogPathCache.get(PLAY_LOG_PATH))
//                    .setIsSmartReply(smartReplyOpen)
//                    .setPlayScriptId(scriptId == null ? "" : scriptId.toString())
//                    .setScriptCategoryId(configDto.getFileDirectory().getCategoryId())
//                    .setVolume(MyDecimalUtil.getFloatVolume(configDto.getAudioSetting().getVolume().getLocal()));
//            //正在播放的音频播放完成后插入到第一条
//            audioQueueService.insertFirstToQueue(audioDto, textToSpeechFrontDto.getPlayerType());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//    }
//
//    @Override
//    public String getUserCount() {
//        return userCountCache.get(USER_COUNT_KEY);
//    }
//
//    @Override
//    public void updateUserCount(UpdateRealTimeDataDto dto) {
//        if (StringUtils.isBlank(dto.getUserCount())) {
//            return;
//        }
//        userCountCache.put(USER_COUNT_KEY, dto.getUserCount());
//    }
//
//    /**
//     * 获取生成音频的模型名称
//     *
//     * @param dto
//     * @param configDto
//     * @return
//     */
//    private static String getAudioModelName(PlayDto dto, ConfigDto configDto) {
//        ConfigDto.ModelSetting modelSetting = configDto.getModelSetting();
//
//        String modelName = "";
//        String speaker = getSpeaker(dto, configDto);
//        if (BvConstants.DEFAULT_SPEAKER.equals(speaker)) {
//            modelName = modelSetting.getAnchor();
//        } else if (BvConstants.ASSISTANT_SPEAKER.equals(speaker)) {
//            modelName = modelSetting.getAssistant();
//        }
//        return modelName;
//    }
//
//    /**
//     * 获取音频的播放器发音人
//     *
//     * @param dto
//     * @param configDto
//     * @return
//     */
//    private static String getSpeaker(PlayDto dto, ConfigDto configDto) {
//
//        String speaker = BvConstants.DEFAULT_SPEAKER;
//        switch (dto.getScriptType()) {
//            case INSERT_AUDIO:
//                speaker = configDto.getInsertAudioSetting().getType();
//                break;
//            case KEYWORD:
//                speaker = configDto.getKeywordSetting().getType();
//                break;
//            case USER_ENTER:
//                speaker = configDto.getUserEnterSetting().getType();
//                break;
//            default:
//                break;
//        }
//        return speaker;
//    }
//
//    /**
//     * 获取文本转语音入参
//     *
//     * @param text
//     * @param modelSetting
//     * @return
//     */
//    public static TextToSpeechFrontDto getTextToSpeechFrontDto(String text, ConfigDto.ModelSetting modelSetting) {
//
//        TextToSpeechFrontDto textToSpeechFrontDto = new TextToSpeechFrontDto();
//        textToSpeechFrontDto.setTopK(modelSetting.getTopK());
//        textToSpeechFrontDto.setTopP(modelSetting.getTopP());
//        textToSpeechFrontDto.setTemperature(modelSetting.getTemperature());
//        textToSpeechFrontDto.setSeed(modelSetting.getSeed());
//        textToSpeechFrontDto.setSpeedFactor(modelSetting.getSpeedFactor());
//        textToSpeechFrontDto.setRepetitionPenalty(modelSetting.getRepetitionPenalty());
//        textToSpeechFrontDto.setText(text);
//        return textToSpeechFrontDto;
//    }
//}
